﻿#include"XQArguments.h"
#include<QWidget>
#include<QApplication>
#include<QDebug>
XQArguments* XQArguments::m_Global=nullptr;
QStringList XQArguments::m_argsList;//命令行参数列表
QMap<QString, QString> XQArguments::m_argsMap;//参数
XQArguments::XQArguments(QObject* parent)
	:QObject(parent)
{
	if(m_argsList.isEmpty())
	{
		parse_arguments();
	}
}

XQArguments::~XQArguments()
{
}

void XQArguments::insert(const QString& key, const QString& value)
{
	if (key.isEmpty() || value.isEmpty())
		return;
	m_argsMap[key] = value;
}

void XQArguments::remove(const QString& key)
{
	m_argsMap.remove(key);
}

QString XQArguments::toArgs()
{
	QString args;
	for (auto it=m_argsMap.begin();it!=m_argsMap.end();it++)
	{
		if(it.key()!="AppPath")
			args += (" " + it.key() + ":" + it.value());
	}
	return std::move(args);
}

bool XQArguments::isArgsMapExist(const QString& key)
{
	if(m_argsMap.find(key)==m_argsMap.end())
		return false;
	return true;
}

QString XQArguments::appPath()
{
	return m_argsMap["AppPath"];
}

QString XQArguments::autoStartType_toString(AutoStartType type)
{
	switch (type)
	{
	case show:return "show";
		break;
	case hide:return "hide";
		break;
	case minimized:return "minimized";
		break;
	default:
		break;
	}
	return QString();
}

QString XQArguments::settingsPath()
{
	if (isArgsMapExist("SettingsPath"))
		return m_argsMap["SettingsPath"];
	return QString();
}

AutoStartType XQArguments::autoStartType()
{
	auto type = m_argsMap["AutoStartType"];
	if (type == "show")
		return AutoStartType::show;
	else if (type == "hide")
		return AutoStartType::hide;
	else if (type == "minimized")
		return AutoStartType::minimized;
	return AutoStartType::show;
}

void XQArguments::setAutoStartWidget(QWidget* widget)
{
	//qInfo() <<"设置显示方式"<< m_argsMap;
	if (widget == nullptr)
		return;
	switch (autoStartType())
	{
	case AutoStartType::show:widget->show(); //qInfo() << "显示";
		break;
	case AutoStartType::hide:widget->hide(); //qInfo() << "隐藏";
		break;
	case AutoStartType::minimized:widget->showMinimized();// qInfo() << "最小化";
		break;
	default:
		break;
	}
}

void XQArguments::setAutoStartType(AutoStartType type)
{
	insert("AutoStartType", autoStartType_toString(type));
}

void XQArguments::setSettingsPath(const QString& path)
{
	insert("SettingsPath", path);
}
bool XQArguments::isArgsListExist(const QString& args)
{
	return m_argsList.contains(args);
}

void XQArguments::connect(const QString& args, std::function<void()> func)
{
	if (isArgsMapExist(args))
	{
		func();
	}
}

void XQArguments::parse_arguments()
{
	m_argsList = QApplication::arguments();
	m_argsMap["AppPath"]= m_argsList[0];
	//qInfo() << m_argsList;
	for (size_t i=1;i< m_argsList.size();i++)
	{
		auto& args = m_argsList[i];
		int nSel = args.indexOf(":");
		if (nSel == -1)
			continue;
		auto key = args.left(nSel);
		auto value = args.mid(nSel+1);
			m_argsMap[key]= value;
	}
	//qInfo() << m_argsMap;
}
